package com.fowo.api.datainterface.util;


import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fowo.api.sys.component.ExecuteScriptEngine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class JScriptUtil {

    @Autowired
    private ExecuteScriptEngine scriptEngine;
    public static final String JSCONTENTFROM = "var data = ${data}; ${jsContent};; ";
//    public static final String JSCONTENTFROM = "var method = function(data) { ${jsContent} };" +
//            "var result = method(${data});" +
//            "if(typeof(result)=='object')" +
//            "{JSON.stringify(result);}else{result;};";


    /**
     * 调用js代码, 处理JSON数据 返回JSON数据
     *
     * @param dataProcessing 数据处理函数
     * @param data           JSON对象/数组
     * @return JSON对象/数组
     */
    public Object callJsFrom(String dataProcessing, Object data, Object args, ServiceImpl<?, ?> service) {
//        dataProcessing = getJsContent(dataProcessing);
        if (StrUtil.isEmpty(dataProcessing)) {
            return data;
        }
        String replace = JSCONTENTFROM.replace("${data}", JsonUtil.getObjectToString(data)).replace("${jsContent}", dataProcessing);
        Object result = null;
        try {
            result = scriptEngine.callJs(replace, args, null, service);
        } catch (Exception ex) {
            Assert.isTrue(false, "执行JS脚本异常！信息:{}", ExceptionUtil.getSimpleMessage(ex));
        }
        try {
            return JsonUtil.getJsonToJsonArray(result);
        } catch (Exception exx) {
            try {
                return JsonUtil.getJsonToJsonArray(StrUtil.toString(result));
            } catch (Exception exxx) {
                try {
                    return JsonUtil.getJsonToBean(result, JSONObject.class);
                } catch (Exception exxxx) {
                    try {
                        return JsonUtil.getJsonToBean(StrUtil.toString(result), JSONObject.class);
                    } catch (Exception exxxxx) {
                        Assert.isTrue(false, "执行JS脚本转换脚本异常！信息:{}", ExceptionUtil.getRootCauseMessage(exxxxx));
                    }
                }
            }
        }
        return result;
    }

    /**
     * 调用js代码, 处理JSON数据 返回JSON数据
     *
     * @param dataProcessing 数据处理函数
     * @param data           JSON对象/数组
     * @return JSON对象/数组
     */
    public JSONObject callJsTo(String dataProcessing, JSONObject data, Object args, ServiceImpl<?, ?> service) {
        if (StrUtil.isEmpty(dataProcessing)) {
            return JsonUtil.getJsonToBean(data, JSONObject.class);
        }
        String replace = JSCONTENTFROM.replace("${data}", JsonUtil.getObjectToString(data)).replace("${jsContent}", dataProcessing);
        Object result = null;
        try {
            result = scriptEngine.callJs(replace, args, null, service);
        } catch (Exception ex) {
            Assert.isTrue(false, "执行JS脚本转异常！信息:{}", ExceptionUtil.getSimpleMessage(ex));
        }
        try {
            return JsonUtil.getJsonToBean(JsonUtil.getObjectToString(result), JSONObject.class);
        } catch (Exception ex) {
            try {
                return JsonUtil.getJsonToBean(StrUtil.toString(result), JSONObject.class);
            } catch (Exception exx) {
                Assert.isTrue(false, "执行JS脚本转换脚本异常！信息:{}", ExceptionUtil.getSimpleMessage(exx));
            }
        }
        return JsonUtil.getJsonToBean(data, JSONObject.class);
    }

    public Object callJsInvoke(String dataProcessing, Object data, Object args, ServiceImpl<?, ?> service) {
//        dataProcessing = getJsContent(dataProcessing);
        if (StrUtil.isEmpty(dataProcessing)) {
            return data;
        }
        String replace = JSCONTENTFROM.replace("${data}", JsonUtil.getObjectToString(data)).replace("${jsContent}", dataProcessing);
        Object result = null;
        try {
            result = scriptEngine.callJs(replace, args, null, service);
        } catch (Exception ex) {
            Assert.isTrue(false, "执行JS脚本异常！信息:{}", ExceptionUtil.getSimpleMessage(ex));
        }
        return result;
    }

    /**
     * 返回js内容
     *
     * @param dataProcessing
     * @return
     */
    public static String getJsContent(String dataProcessing) {
        if (StrUtil.isNotEmpty(dataProcessing) && dataProcessing.length() > 0) {
            // 获取位置
            int indexOf = dataProcessing.indexOf("{");
            if (indexOf > -1) {
                dataProcessing = dataProcessing.substring(indexOf + 1);
            }
            int lastIndexOf = dataProcessing.lastIndexOf("}");
            if (lastIndexOf > -1) {
                dataProcessing = dataProcessing.substring(0, lastIndexOf);
            }
            dataProcessing = StrUtil.replaceLast(dataProcessing, "return", "", true);
            return dataProcessing;
        }
        return "";
    }

}
